<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v4;


use app\api\controller\external;
use app\api\model\Authority;
use app\api\model\Community;
use app\index\model\Pdf;
use think\Controller;
use think\Exception;
use think\Request;
use foxyZeng\huyi\HuYiSMS;
use  app\api\model\OrderModel;
use app\api\validate;
use Think\Db;
use  app\api\model\Approval;

class Order extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;
    
    
    public function _initialize()
    {
        $this->model   =new Authority();
        $this->pdf     =new Pdf();
        $this->us      =Authority::check(1);
        $this->newTime =strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -5 minutes")));
        $this->endTime =strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -10 minutes")));
        $this->overtime=strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s', strtotime('+1minute')))));
    }
    
    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need(OrderModel $orderModel)
    {
        $data          =$this->model->post(['channel_id', 'pro_id', 'province_id', 'city_id', 'county_id', 'addres', 'contacts', 'telephone', 'remarks', 'logo', 'lat', 'lng']);
        $Order_Validate=new validate\Order_Validate();
        if (!$Order_Validate->check($data)) {
            r_date($Order_Validate->getError(), 300);
        }
        if (!is_mobile($data['telephone'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        
        if ($data['province_id']) {
            $province=db('province')->where(['province'=>['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id=db('city')->where(['city'=>['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county=db('county')->where(['county'=>['like', "%{$data['county_id']}%"]])->value('county_id');
        }
        $res=$orderModel::create([
            'channel_id'  =>$data['channel_id'],//渠道
            'order_no'    =>order_sn(),//订单号
            'pro_id'      =>$data['pro_id'],//一级问题
            'province_id' =>$province,//省
            'city_id'     =>$city_id,//市
            'county_id'   =>$county,//区
            'addres'      =>$data['addres'],//地址
            'contacts'    =>$data['contacts'],//联系人
            'telephone'   =>$data['telephone'],//联系电话
            'remarks'     =>$data['remarks'],//备注
            'logo'        =>!empty($data['logo'])? serialize(json_decode($data['logo'], true)) : '',//图片
            'state'       =>1,//待指派
            'assignor'    =>$this->us['user_id'],//指派人
            'created_time'=>time(),//创建时间
            'update_time' =>time(),//创建时间
            'lat'         =>$data['lat'],//创建时间
            'lng'         =>$data['lng'],//创建时间
        ]);
        
        if ($res) {
            db('remind')->insertGetId([
                'admin_id'=>$this->us['user_id'],
                'order_id'=>$res->order_id,
                'time'    =>time(),
                'stater'  =>1,
                'tai'     =>1,
            ]);
            $content="店长输入的订单";
            db('message')->insertGetId([
                'type'    =>6,
                'content' =>$content,
                'order_id'=>$res->order_id,
                'time'    =>time(),
                'already' =>1,
                'user_id' =>$this->us['user_id'],
            ]);
            r_date([], 200, '新增成功');
        }
        r_date([], 300, '新增失败');
        
    }
    
    /**
     * @throws Exception
     * 提醒个数
     */
    public function Unread()
    {
        
        $coun1=db('remind')->where(['admin_id'=>$this->us['user_id'], 'stater'=>1, 'tai'=>1])->count();
        $coun2=db('remind')->where(['admin_id'=>$this->us['user_id'], 'stater'=>2, 'tai'=>1])->count();
//        $coun3 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 3, 'tai' => 1])->count();
//        $coun4 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 4, 'tai' => 1])->count();
//        $coun5 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 5, 'tai' => 1])->count();
//        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();
        
        $couns=[
            'zhu'=>[
                0=>$coun1,
                1=>$coun2,
            ],
        ];
        
        r_date($couns, 200);
        
        
    }
    
    /**
     * 修改地址
     * cate_id 二级id
     */
    public function edit_di(OrderModel $orderModel)
    {
        $data=$this->model->post(['order_id', 'province_id', 'city_id', 'county_id', 'addres']);
        if ($data['province_id']) {
            $province=db('province')->where(['province'=>['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id=db('city')->where(['city'=>['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county=db('county')->where(['county'=>['like', "%{$data['county_id']}%"]])->value('county_id');
        }
        $res=$orderModel::update(['province_id'=>$province, 'city_id'=>$city_id, 'county_id'=>$county, 'addres'=>$data['addres'],], ['order_id'=>$data['order_id']]);
        
        if ($res) {
            r_date([], 200, '新增成功');
        }
        r_date([], 300, '新增失败');
        
    }
    
    /**
     * 获取渠道
     */
    public function get_my_qu()
    {
        $res=db('chanel')->field('id,title')->where('type', 1)
            ->select();
        r_date($res);
    }
    
    /**
     * 获取问题
     */
    public function get_my_wen()
    {
        $res=db('goods_category')
            ->field('goods_category.title,goods_category.id')
            ->where(['pro_type'=>1, 'is_enable'=>1, 'parent_id'=>0, 'type'=>1])
            ->select();
        r_date($res);
    }
    
    /**
     * 智能报价
     */
    public function IntelligentQuotation()
    {
        $res=db('goods_category')
            ->field('title,parent_id,id,type')
            ->where(['pro_type'=>1, 'is_enable'=>1])
            ->select();
        foreach ($res as $v) {
            if ($v['parent_id'] == 0 && $v['type'] == 2) {
                $op[]=$v;
            } else if ($v['type'] == 1) {
                $opp[]=$v;
            }
        }
        foreach ($op as $v) {
            $data=[];
            foreach ($opp as $item) {
                if ($v['id'] == $item['parent_id']) {
                    $data[]=$item;
                }
            }
            $da[]=[
                'title'=>$v['title'],
                'data' =>$data,];
        }
        foreach ($da as $kef=>$item) {
            $p='';
            foreach ($item['data'] as $k=>$it) {
                $p.=$it['id'] . ',';
            }
            $p    =substr($p, 0, - 1);
            $res  =db('goods_category')
                ->field('title,parent_id,id,type')
                ->where(['pro_type'=>1, 'is_enable'=>1, 'parent_id'=>['in', $p]])
                ->select();
            $daa[]=[
                'title'=>$item['title'],
                'data' =>$res,
            ];
        }
        r_date($daa);
    }
    
    /**
     * 获取智能报价
     */
    public function smartOptions()
    {
        $data=Request::instance()->post(['id']);
        $res =db('goods_category')
            ->field('mandatory,optional,id,kind')
            ->where(['id'=>['in', $data['id']], 'pro_type'=>1, 'is_enable'=>1])
            ->select();
        
        $mandatory   ='';
        $optional    ='';
        $Intelligence='';
        
        foreach ($res as $i) {
            if (!empty($i['mandatory']) && $i['kind'] == 2) {
                $Intelligence.=$i['mandatory'] . ',';
            }
            if (!empty($i['mandatory']) && $i['kind'] == 1) {
                $mandatory.=$i['mandatory'] . ',';
            }
            if (!empty($i['optional']) && $i['kind'] == 1) {
                $optional.=$i['optional'] . ',';
            }
        }
        $pr=[];
        if (!empty($mandatory)) {
            $mandatory=substr($mandatory, 0, - 1);
            $rdetailed=db('detailed')
                ->where(['serial'=>['in', $mandatory], 'tao'=>0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['detailed_id'];
                $pr[$k]['projectMoney']=$l['artificial'];
                $pr[$k]['projectTitle']=$l['detailed_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =1;
                $pr[$k]['type']        =1;
                unset($rdetailed[$k]);
            }
            
        }
        
        if (!empty($Intelligence)) {
            
            $Intelligence=substr($Intelligence, 0, - 1);
            $rdetailed   =db('detailed')->whereIn('serial', $Intelligence)->where('tao', 0)->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            
            foreach ($rdetailed as $k=>$l) {
                $prr[$k]['projectId']   =$l['detailed_id'];
                $prr[$k]['projectMoney']=$l['artificial'];
                $prr[$k]['projectTitle']=$l['detailed_title'];
                $prr[$k]['title']       =$l['title'];
                $prr[$k]['number']      =$l['number'];
                $prr[$k]['tao']         =1;
                $prr[$k]['type']        =2;
                unset($rdetailed[$k]);
            }
            
            $pr=array_merge($pr, $prr);
            
        }
        
        $option=[];
        if (!empty($optional)) {
            $optional =substr($optional, 0, - 1);
            $rdetailed=db('detailed')->where(['serial'=>['in', $optional], 'tao'=>0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k=>$l) {
                $option[$k]['projectId']   =$l['detailed_id'];
                $option[$k]['projectMoney']=$l['artificial'];
                $option[$k]['projectTitle']=$l['detailed_title'];
                $option[$k]['title']       =$l['title'];
                $option[$k]['number']      =$l['number'];
                $option[$k]['tao']         =1;
                $option[$k]['type']        =1;
                unset($rdetailed[$k]);
            }
        }
        r_date([
            'mandatory'           =>$pr,
            'nonEssentialElection'=>$option,
        ]);
    }
    
    /**
     * 获取标题
     */
    public function Material()
    {
        $res=db('stock')
            ->field('id,company,stock_name,latest_cost,type,class_table')
            ->select();
        $po =array_merge(array_unique(array_column($res, 'type')));
        foreach ($po as $k=>$v) {
            $data=[];
            foreach ($res as $value) {
                if ($v == $value['type']) {
                    $data['title'] =$value['class_table'];
                    $data['type']  =$v;
                    $data['data'][]=$value;
                    $data['count'] =count($data['data']);
                }
            }
            unset($data['data']);
            $r[]=$data;
        }
        
        $custom         =[];
        $cpurchase      =[];
        $custom_material=db('custom_material')
            ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
            ->where('number', 'neq', 0)
            ->field('id,company,stock_name,latest_cost')
            ->select();
        
        
        $custom[0]['title']='自购入库材料';
        $custom[0]['type'] =0;
        $custom[0]['count']=count($custom_material);
        
        $cpurchase_usage=db('purchase_usage')
            ->where(['store_id'=>$this->us['store_id']])
            ->where('status', 3)
            ->where('number', 'neq', 0)
            ->field('id,company,stock_name,latest_cost')
            ->select();
        
        $cpurchase[0]['title']='采购入库材料';
        $cpurchase[0]['type'] =99;
        $cpurchase[0]['count']=count($cpurchase_usage);
        
        r_date(array_merge(array_merge($r, $custom), $cpurchase), 200);
    }
    
    /**
     * 获取列表
     */
    public function Material_list()
    {
        $data=Request::instance()->post(['type']);
        if ($data['type'] == 0) {
            $custom=db('custom_material')
                ->field('id,company,stock_name,latest_cost,number')
                ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
                ->select();
        } else{
            $custom=db('stock')
                ->field('id,company,stock_name,latest_cost')
                ->where('type', $data['type'])
                ->select();
        }
        
        
        r_date($custom, 200);
    }

//材料费用提交
    public function material_usage(\app\api\model\Common $common)
    {
        $data          =Request::instance()->post();
        $material_usage=json_decode($data['materialJson'], true);
        db()->startTrans();
        try {
            
            $p=0;
            foreach ($material_usage as $datum) {
                $number=$common->Calculation($datum, $data['order_id'], $this->us['user_id'], 3);
                if ($number['code'] == 'no') {
                    throw new Exception($number['msg']);
                }
                $pp=[
                    'order_id'       =>$data['order_id'],
                    'material_name'  =>$datum['material_name'],
                    'Material_id'    =>$datum['Material_id'],
                    'square_quantity'=>$datum['square_quantity'],
                    'unit_price'     =>$datum['unit_price'],
                    'type'           =>$datum['type'],
                    'company'        =>$datum['company'],
                    'total_price'    =>round($datum['unit_price'] * $datum['square_quantity'], 2),
                    'user_id'        =>$this->us['user_id'],
                    'created_time'   =>time(),
                    'shopowner_id'   =>$this->us['user_id'],
                ];
                
                $material_usage=db('material_usage')->insertGetId($pp);
                db('usage_record')->insertGetId([
                    'id'             =>$material_usage,
                    'type'           =>$datum['type'],
                    'user_id'        =>$this->us['user_id'],
                    'number'         =>$datum['square_quantity'],
                    'created_time'   =>time(),
                    'order_id'       =>$data['order_id'],
                    'original_number'=>$number['number'],
                    'unified'=>$number['unified'],
                ]);
                
                $p+=$pp['total_price'];
                
            }
            if ((string)$p != $data['allMoney']) {
                db()->rollback();
                throw new Exception('金额错误');
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 费用报销
     */
    public function reimbursement(Approval $approval)
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $my_string                  =explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
            if (empty($data['work_wechat_user_id'])) {
                throw new Exception('请联系公司');
            }
            $data['content']=$data['remarks'];
            $wechatObj_data =$approval->Reimbursement($data, $my_string);
            if ($wechatObj_data['errcode'] != 0) {
                throw new Exception('企业微信提交失败');
            }
            $op=[
                'order_id'          =>$data['order_id'],
                'reimbursement_name'=>$data['name'],
                'money'             =>$data['money'],
                'voucher'           =>!empty($data['img'])? serialize($my_string) : '',
                'created_time'      =>time(),
                'user_id'           =>$this->us['user_id'],
                'status'            =>0,
                'sp_no'             =>$wechatObj_data['sp_no'],
                'content'           =>$data['remarks'],
                'classification'    =>$data['type'],
                'submission_time'   =>time(),
                'shopowner_id'   =>$this->us['user_id'],
            ];
            
            db('reimbursement')->insert($op);
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
        
    }
    
    /*
     * 自定义删除
     */
    public function custom_material_delect()
    {
        $data=Request::instance()->post();
        
        db('custom_material')->where('id', $data['id'])->update(['status'=>1]);
        
        r_date(null, 200);
        
        
    }
    
    /**
     * 获取材料
     */
    public function Material_translate()
    {
        $data=$this->model->post();
        $res =db('stock')
            ->field('id,company,stock_name,latest_cost,type');
        if (isset($data['title']) && $data['title'] != '') {
            $res->where(['stock_name'=>['like', "%{$data['title']}%"]]);
        }
        $res=$res->select();
        r_date($res, 200);
    }
    
    /**
     * 获取项目一级标题
     */
    public function get_my_ge()
    {
        $data=Request::instance()->post(['page'=>1, 'limit'=>10]);
        $res =db('product_chan')
            ->where(['parents_id'=>0, 'pro_types'=>1])
            ->field('product_title,product_id')
            ->select();
        foreach ($res as $k=>$v) {
            $res[$k]['count']=db('product_chan')->where(['parents_id'=>$v['product_id'], 'pro_types'=>1])->count();
        }
        $re['tao']     =0;
        $re['detailed']=$res;
        $rdetailed     =db('detailed')->where(['detaileds_id'=>0, 'display'=>1])->field('detailed_id,detailed_title')->page($data['page'], $data['limit'])->select();
        foreach ($rdetailed as $k=>$v) {
            $rdetailed[$k]['count']=db('detailed')->where(['detaileds_id'=>$v['detailed_id']])->count();
        }
        $r['tao']     =1;
        $r['detailed']=$rdetailed;
        $data         =[
            0=>$re,
            1=>$r,
        ];
        r_date($data);
    }
    
    /**
     * 获取项目二级标题
     */
    public function get_my_er()
    {
        $data=Request::instance()->post(['type', 'detailed', 'page', 'limit']);
        if ($data['type'] == 0) {
            
            $rdetailed=db('product_chan')->where(['parents_id'=>$data['detailed'], 'pro_types'=>1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_id,product_title,parents_id,un.title,prices')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['product_id'];
                $pr[$k]['projectMoney']=$l['prices'];
                $pr[$k]['projectTitle']=$l['product_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =0;
                unset($rdetailed[$k]);
            }
        } elseif ($data['type'] == 1){
            $detailed=db('detailed')->where(['detaileds_id'=>$data['detailed'], 'tao'=>0, 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial')->page($data['page'], $data['limit'])->select();
            foreach ($detailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['detailed_id'];
                $pr[$k]['projectMoney']=$l['artificial'];
                $pr[$k]['projectTitle']=$l['detailed_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =1;
            }
        }
        r_date($pr);
    }
    
    /**
     * 获取项目二级标题
     */
    public function mandatory()
    {
        $data     =Request::instance()->post(['projectId']);
        $prr      =[];
        $rdetailed=db('detailed')->field('serial')->where(['detailed_id'=>$data['projectId']])->find();
        if (!empty($rdetailed)) {
            $detailed_list=db('detailed_list')->field('relation')->where(['serial_id'=>['in', $rdetailed['serial']]])->find();
            if (!empty($detailed_list)) {
                $rdetailed=db('detailed')->where(['serial'=>['in', $detailed_list['relation']], 'tao'=>0, 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial')->select();
                foreach ($rdetailed as $k=>$l) {
                    $prr[$k]['projectId']   =$l['detailed_id'];
                    $prr[$k]['projectMoney']=$l['artificial'];
                    $prr[$k]['projectTitle']=$l['detailed_title'];
                    $prr[$k]['title']       =$l['title'];
                    $prr[$k]['tao']         =1;
                }
            }
        }
        r_date($prr);
    }
    
    /**
     * 基建赠送项目
     */
    public function get_zeng()
    {
        $res=db('product_chan')->where(['parents_id'=>['neq', 0], 'pro_types'=>1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_title,parents_id,un.title,prices')->order('product_id desc')->select();
        foreach ($res as $k=>$l) {
            
            $pr[$k]['projectMoney']=$l['prices'];
            $pr[$k]['projectTitle']=$l['product_title'];
            $pr[$k]['title']       =$l['title'];
            $pr[$k]['tao']         =0;
            unset($res[$k]);
        }
        $rdetailed=db('detailed')->where(['detaileds_id'=>['neq', 0], 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_title,detaileds_id,un.title,artificial')->order('detailed_id desc')->select();
        foreach ($rdetailed as $k=>$l) {
            $pr1[$k]['projectMoney']=$l['artificial'];
            $pr1[$k]['projectTitle']=$l['detailed_title'];
            $pr1[$k]['title']       =$l['title'];
            $pr1[$k]['tao']         =1;
            unset($rdetailed[$k]);
        }
        
        $data=array_merge($pr1, $pr);
        r_date($data);
    }
    
    /**
     * 基建搜索
     */
    public function despair()
    {
        $data=$this->model->post(['con']);
        $list=db('detailed')->field('detailed.detailed_title,detailed.detailed_id,detailed.artificial,un.title,detailed.tao')->where(['detaileds_id'=>['neq', 0], 'detailed_title|serial'=>['like', "%{$data['con']}%"], 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->order('detailed_id desc')->select();
        $pr  =[];
        foreach ($list as $k=>$l) {
            
            $pr[$k]['tao']         =1;
            $pr[$k]['projectId']   =$l['detailed_id'];
            $pr[$k]['projectMoney']=$l['artificial'];
            $pr[$k]['projectTitle']=$l['detailed_title'];
            $pr[$k]['title']       =$l['title'];
            $pr[$k]['tao2']        =$l['tao'];
            
            unset($list[$k]);
        }
        r_date($pr);
    }
    
    /**
     * 基检搜索
     */
    public function set_jian()
    {
        
        $data=$this->model->post(['tao', 'detailed', 'sou1']);
        $s   =substr($data['detailed'], 0, - 1);  //利用字符串截取函数消除最后一个逗号
        if ($data['tao'] == 0) {
            $product=db('product_chan')->where('product_id', 'in', $s)->field('parents_id,product_id,product_title')->select();
            foreach ($product as $o) {
                $product_chan=db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id'=>$o['product_id'], 'parents_id'=>$o['parents_id']])->field('product_title,prices,u.title,product_title,product_id')->select();
                foreach ($product_chan as $k=>$l) {
                    $pr[$k]['projectId']   =$l['product_id'];
                    $pr[$k]['projectMoney']=$l['prices'];
                    $pr[$k]['projectTitle']=$l['product_title'];
                    $pr[$k]['title']       =$l['title'];
                    $pr[$k]['tao']         =0;
                    unset($product_chan[$k]);
                }
                $s  =[
                    'big_title'=>db('product_chan')->where(['product_id'=>$o['parents_id']])->value('product_title'),
                    'data'     =>$pr,
                    'tao'      =>0,
                ];
                $p[]=$s;
                
            }
            r_date($p, 200);
            
        } elseif ($data['tao'] == 1){
            if (!empty($data['detailed'])) {
                
                $product=db('detailed')->where(['detailed_id'=>['in', $s]])->field('detaileds_id,detailed_id')->select();
                foreach ($product as $o) {
                    $product_chan=db('detailed')->join('unit u', 'detailed.un_id=u.id', 'left')->where(['detailed_id'=>$o['detailed_id'], 'detaileds_id'=>$o['detaileds_id']])->field('detailed_id,detailed_title,artificial,u.title')->select();
                    foreach ($product_chan as $k=>$l) {
                        $pr[$k]['projectId']   =$l['detailed_id'];
                        $pr[$k]['projectMoney']=$l['artificial'];
                        $pr[$k]['projectTitle']=$l['detailed_title'];
                        $pr[$k]['title']       =$l['title'];
                        $pr[$k]['tao']         =1;
                        unset($product_chan[$k]);
                    }
                    $s  =[
                        'big_title'=>db('detailed')->where(['detailed_id'=>$o['detaileds_id']])->value('detailed_title'),
                        'data'     =>$pr,
                        'tao'      =>1,
                    ];
                    $p[]=$s;
                }
                
            }
            if (!empty($data['sou1'])) {
                $s=substr($data['sou1'], 0, - 1);  //利用字符串截取函数消除最后一个逗号
                $m=explode(",", $s);
                
                foreach ($m as $h) {
                    $pro =db('product_chan')->where(['product_title'=>$h])->field('parents_id,product_id')->find();
                    $pk[]=$pro;
                }
                foreach ($pk as $o) {
                    $produ=db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id'=>$o['product_id'], 'parents_id'=>$o['parents_id']])->select();
                    foreach ($produ as $k=>$l) {
                        $kl[$k]['projectId']   =$l['product_id'];
                        $kl[$k]['projectMoney']=$l['prices'];
                        $kl[$k]['projectTitle']=$l['product_title'];
                        $kl[$k]['title']       =$l['title'];
                        $kl[$k]['tao']         =0;
                        unset($produ[$k]);
                    }
                    $s   =[
                        'big_title'=>db('product_chan')->where(['product_id'=>$o['parents_id']])->value('product_title'),
                        'tao'      =>0,
                        'data'     =>$kl,
                    ];
                    $p1[]=$s;
                }
            }
            if (!empty($data['sou1']) && !empty($data['detailed'])) {
                r_date(array_merge($p, $p1), 200);
            } elseif (!empty($data['detailed'])){
                r_date($p, 200);
            } elseif (!empty($data['sou1'])){
                r_date($p1, 200);
            }
        } elseif ($data['tao'] == 2){
            $object=db('information')->where(['id'=>['in', $s], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
            foreach ($object as $o) {
                $product_chan=db('information')->where(['id'=>$o['id'], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
                foreach ($product_chan as $k=>$l) {
                    $pr[$k]['projectId']   =$l['id'];
                    $pr[$k]['projectMoney']=$l['un_Price'];
                    $pr[$k]['projectTitle']=$l['class_b'];
                    $pr[$k]['title']       =$l['company'];
                    $pr[$k]['tao']         =2;
                    unset($product_chan[$k]);
                }
                $s  =[
                    'big_title'=>$l['class_a'],
                    'data'     =>$pr,
                    'tao'      =>2,
                ];
                $p[]=$s;
            }
            r_date($p, 200);
        }
        
        
    }
    
    
    /**
     * 基检编辑
     */
    public function updaty()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['fen'] == 0) {
                $product_chan=db('product_chan')->where('product_id', $data['projectId'])->find();
                $title       =db('unit')->where('id', $product_chan['units_id'])->value('title');
                $user        =[
                    'company'   =>!empty($title)? $title : '',//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$product_chan['prices'],//单价
                    'rule'      =>$product_chan['price_rules'],//规则
                    'zhi'       =>$data['zhi'],//规则
                    'to_price'  =>$product_chan['prices'] * $data['square'],//总价
                    'class_b'   =>$product_chan['product_title'],//三
                    'projectId' =>$data['projectId'],//三
                    'fen'       =>0,//状态
                    'class_a'   =>db('product_chan')->where(['product_id'=>$product_chan['parents_id']])->value('product_title'),//三
                    'gold_suite'=>1,//三
                ];
            } elseif ($data['fen'] == 1){
                $detailed=db('detailed')->where('detailed_id', $data['projectId'])->find();
                $title   =db('unit')->where('id', $detailed['un_id'])->value('title');
                $user    =[
                    'company'   =>!empty($title)? $title : '',//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$detailed['artificial'],//单价
                    'rule'      =>$detailed['rmakes'],//规则
                    'zhi'       =>$data['zhi'],//规则
                    'to_price'  =>$detailed['artificial'] * $data['square'],//总价
                    'class_b'   =>$detailed['detailed_title'],//三
                    'projectId' =>$data['projectId'],//三
                    'fen'       =>1,//状态
                    'class_a'   =>db('detailed')->where(['detailed_id'=>$detailed['detaileds_id']])->value('detailed_title'),//三
                    'gold_suite'=>1,//三
                ];
                
            } elseif ($data['fen'] == 2){
                $user=[
                    'company'   =>$data['company'],//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$data['prices'],//单价
                    'to_price'  =>$data['square'] * $data['prices'],//总价
                    'zhi'       =>$data['zhi'],//规则
                    'fen'       =>2,//状态
                    'projectId' =>$data['projectId'],//三
                    'class_b'   =>$data['class_b'],//三
                    'class_a'   =>$data['class_a'],//三
                    'gold_suite'=>1,//三
                ];
            }
            $res1=db('capital')->where(['capital_id'=>$data['capital_id']])->field('ordesr_id,to_price')->find();
            $r   =db('order')->where(['order_id'=>$res1['ordesr_id']])->field('ification,order_id')->find();
            if ($r['ification'] == 2) {
                $thro=db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->field('through_id')->find();
                if ($thro) {
                    $ca=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money')->find();
                } else{
                    $ca=db('envelopes')->where(['ordesr_id'=>$r['order_id'], 'through_id'=>0])->field('give_money')->find();
                }
                $cap   =db('capital')->where(['ordesr_id'=>$r['order_id'], 'types'=>1, 'enable'=>1])->sum('to_price');
                $amount=$cap - $res1['to_price'] + $user['to_price'];
                $p     =$ca['give_money'];
            } else{
                $ca    =db('capital')->where(['ordesr_id'=>$r['order_id'], 'types'=>1, 'enable'=>1])->field('sum(to_price),sum(give_money)')->find();
                $amount=$ca['sum(to_price)'] - $res1['to_price'] + $user['to_price'];
                $p     =$ca['sum(give_money)'];
            }
            
            if (($amount * 0.1) < $p) {
                r_date(null, 300, '优惠金额不能大于订单总价的10%');
            }
            $p3=db('capital')->where(['capital_id'=>$data['capital_id']])->update($user);
            if ($data['yc'] == 1) {
                $res2=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'enable'=>1, 'programme'=>3, 'types'=>1])->sum('to_price');
                db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->update(['amount'=>$res2]);
            }
            $cap=db('order')->where(['order_id'=>$res1['ordesr_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($res1['ordesr_id'], 1, $cap);
            if ($p3) {
                db()->commit();
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * 基检增项
     */
    public function amplification()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $cap  ='';
            $order=db('order')->where('order_id', $data['order_id'])->field('ification,order_no,state')->find();
            if ($order['state'] > 3) {
                $Increment=1;
            } else{
                $Increment=0;
            }
            if ($data['yc'] == 1) {
                $programme=3;
            } else{
                $programme=1;
            }
            if ($order['ification'] == 1) {
                $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'programme'=>1])->order('capital_id desc')->find();
                $give_a =$capital['give_a'];//三
                $give_b =$capital['give_a'];//三
                $wen_a  =$capital['wen_a'];//一级分类
                $wen_b  =$capital['wen_b'];//二
                $wen_c  =$capital['wen_c'];//二
            } else{
                $give_a='';//三
                $give_b='';//三
                $wen_a ='';//一级分类
                $wen_b ='';//二
                $wen_c ='';//二
            }
            if ($data['company']) {
                $op=json_decode($data['company']);
                $op=$this->object2array($op);
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'    =>$wen_a,
                            'wen_b'    =>$wen_b,
                            'wen_c'    =>$wen_c,
                            'company'  =>$v['unit'],//单位
                            'square'   =>$v['fang'],//方量
                            'un_Price' =>$product_chan['prices'],//单价
                            'rule'     =>$product_chan['price_rules'],//规则
                            'zhi'      =>$v['zhi'],//质保
                            'types'    =>1,//状态
                            'fen'      =>0,//状态
                            'to_price' =>$product_chan['prices'] * $v['fang'],//总价
                            'crtime'   =>time(),
                            'ordesr_id'=>$data['order_id'],
                            'class_a'  =>$v['title'],//三
                            'class_b'  =>$v['projectTitle'],//三
                            'enable'   =>1,//三
                            'programme'=>$programme,//三
                            'give_a'   =>$give_a,//赠送项目
                            'give_b'   =>$give_b,
                            'projectId'=>$v['product_id'],//三
                            'increment'=>$Increment,//三
                        ];
                        
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'    =>'',
                            'wen_b'    =>'',
                            'wen_c'    =>'',
                            'company'  =>$v['unit'],//单位
                            'square'   =>$v['fang'],//方量
                            'un_Price' =>$product_chan['artificial'],//单价
                            'rule'     =>$product_chan['rmakes'],//规则
                            'zhi'      =>$v['zhi'],//质保
                            'types'    =>1,//状态
                            'fen'      =>1,//状态
                            'to_price' =>$product_chan['artificial'] * $v['fang'],//总价
                            'crtime'   =>time(),
                            'ordesr_id'=>$data['order_id'],
                            'class_a'  =>$v['title'],//三
                            'class_b'  =>$v['projectTitle'],//三
                            'qi_rmakes'=>'',
                            'enable'   =>1,//三
                            'programme'=>$programme,//三
                            'give_a'   =>$give_a,//赠送项目
                            'give_b'   =>$give_b,
                            'projectId'=>$v['product_id'],//三
                            'increment'=>$Increment,//三
                        ];
                        
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'    =>'',
                            'wen_b'    =>'',
                            'wen_c'    =>'',
                            'company'  =>$v['unit'],//单位
                            'square'   =>$v['fang'],//方量
                            'un_Price' =>$v['prices'],//单价
                            'ordesr_id'=>$data['order_id'],
                            'rule'     =>'',//规则
                            'zhi'      =>$v['zhi'],//质保
                            'types'    =>1,//状态
                            'fen'      =>2,//状态
                            'to_price' =>$v['fang'] * $v['prices'],//总价
                            'crtime'   =>time(),
                            'class_a'  =>$v['title'],//三
                            'class_b'  =>$v['projectTitle'],//三
                            'qi_rmakes'=>'',
                            'enable'   =>1,//三
                            'programme'=>$programme,//三
                            'give_a'   =>$give_a,//赠送项目
                            'give_b'   =>$give_b,
                            'projectId'=>$v['product_id'],//三
                            'increment'=>$Increment,
                        ];
                        
                    }
                    $capital=db('capital')->insertGetId($users);
                    $cap    .=$capital . ',';
                    
                }
                
                
            }
            if (isset($data['id']) && $data['id'] != 0) {
                $allow=db('allow')->where('id', $data['id'])->find();
                $s    =substr($cap, 0, - 1);
                $c    =$allow['capital_id'] . ',' . $s;
                db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
            }
            $cap=db('order')->where(['order_id'=>$data['order_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($data['order_id'], 1, $cap);
            if ($data['yc'] == 1) {
                $WeChat=0;
                $s     ='';
                $res1  =db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'programme'=>3, 'types'=>1])->field('capital_id,to_price')->select();
                foreach ($res1 as $item) {
                    $WeChat+=$item['to_price'];
                    $s     .=$item["capital_id"] . ',';
                }
                $s=substr($s, 0, - 1);
                db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->update(['amount'=>$WeChat, 'capital_id'=>$s]);
            }
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 基检删除
     */
    public function del()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $res1    =db('capital')->where(['capital_id'=>$data['capital_id']])->field('ordesr_id')->find();
            $to_price=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1])->sum('to_price');
            
            $cap=db('order')->where(['order_id'=>$res1['ordesr_id']])->field('ification,planned,appointment')->find();
            
            if ($cap['ification'] == 2) {
                $give_money=db('envelopes')->where(['ordesr_id'=>$res1['ordesr_id'], 'through_id'=>0])->field('give_money')->find();
                if ($to_price < $give_money['give_money']) {
                    r_date([], 300);
                }
                db('capital')->where(['capital_id'=>$data['capital_id']])->update(['types'=>2]);
            } else{
                $capital=db('capital')->where(['capital_id'=>$data['capital_id'], 'types'=>1])->field('give_money')->find();
                if ($to_price < $capital['give_money']) {
                    r_date([], 300);
                }
                if ($capital['give_money'] != 0) {
                    db('capital')->where(['capital_id'=>$data['capital_id']])->update(['types'=>2]);
                    $capital_id=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1])->field('capital_id')->order('capital_id desc')->find();
                    db('capital')->where(['capital_id'=>$capital_id['capital_id']])->update(['give_money'=>$capital['give_money']]);
                } else{
                    db('capital')->where(['capital_id'=>$data['capital_id']])->update(['types'=>2]);
                }
            }
            if ($data['yc'] == 1) {
                $thro      =db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->order('th_time desc')->find();
                $give_money=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money')->find();
                if ($to_price < $give_money['give_money']) {
                    r_date([], 300);
                }
                $res2=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'enable'=>1, 'programme'=>3, 'types'=>1])->sum('to_price');
                db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->update(['amount'=>$res2]);
            }
            
            if (isset($data['id']) && $data['id'] != 0) {
                $allow=db('allow')->where('id', $data['id'])->find();
                $allow=explode(',', $allow['capital_id']);
                $c    ='';
                foreach ($allow as $k=>$v) {
                    if ($v != $data['capital_id']) {
                        $c.=$v . ',';
                    }
                }
                $c=substr($c, 0, - 1);
                db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
            }
            $this->pdf->put($res1['ordesr_id'], 1, $cap);
            $uss['store_code_id']=$data['capital_id'];
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 基检跟新公共
     */
    public function up()
    {
        $data =Request::instance()->post();
        $order=db('order')->where('order_id', $data['ordesr_id'])->field('ification')->find();
        db()->startTrans();
        if ($order['ification'] == 2) {
            $oi=[
                'wen_a'       =>$data['wen_a'],//一级分类
                'give_b'      =>substr($data['give_b'], 0, - 1),//一级分类
                'gong'        =>$data['gong'],
                'give_remarks'=>$data['give_remarks'],//备注
                'give_money'  =>$data['give_money'],//优惠金额
                'capitalgo'   =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
            ];
            db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update($oi);
        } else{
            $capital=substr($data['capital'], 0, - 1);
            $capital=explode(',', $capital);
            foreach ($capital as $k) {
                $cap=db('capital')->where(['capital_id'=>$k, 'types'=>1, 'enable'=>1])->field('give_money')->find();
                if ($cap['give_money'] != 0) {
                    $oi=[
                        'give_money'  =>$data['give_money'],
                        'capitalgo'   =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                        'give_b'      =>!empty($data['give_b'])? $data['give_b'] : '',
                        'gong'        =>$data['gong'],
                        'give_remarks'=>$data['give_remarks'],
                    ];
                    db('capital')->where(['capital_id'=>$k, 'types'=>1, 'enable'=>1])->update($oi);
                } else{
                    $oi=[
                        'capitalgo'   =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                        'give_b'      =>!empty($data['give_b'])? $data['give_b'] : '',
                        'gong'        =>$data['gong'],
                        'give_remarks'=>$data['give_remarks'],//备注
                    ];
                    db('capital')->where(['capital_id'=>$k, 'types'=>1, 'enable'=>1])->update($oi);
                }
                
            }
        }
        $uss['order_id']      =$data['ordesr_id'];
        $uss['discount']      =$oi['give_money'];
        $uss['plan_work_time']=$data['gong'];
        $result               =send_post(UIP_SRC . "/support-v1/order/edit", $uss);
        $results              =json_decode($result, true);
        if ($results['code'] == 200) {
            db()->commit();
            $cap=db('order')->where(['order_id'=>$data['ordesr_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($data['ordesr_id'], 1, $cap);
            r_date(null, 200);
        }
        db()->rollback();
        r_date(null, 300);
        
        
    }
    
    /**
     * 电子合同
     */
    public function sign()
    {
        $data=Request::instance()->post();
        $op  =db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->find();
        $sign=[];
        $share=0;
        if(isset($data['share']) && $data['share']==1){
            $share=['share'=>1];
        }
        if ($op) {
            $sign=[
                'idnumber' =>$data['idnumber'],
                'username' =>$data['username'],
                'order_id' =>$data['order_id'],
                'user_id'  =>$this->us['user_id'],
                'addtime'  =>strtotime($data['addtime']),
                'uptime'   =>strtotime($data['uptime']),
                'addres'   =>$data['addres'],
                'autograph'=>$data['autograph'],
                'ding'     =>0,
                'zhong'    =>0,
                'wei'      =>0,
                'b1'       =>0,
                'b2'       =>0,
                'b3'       =>0,
                'con_time' =>time(),
                ];
            if($op['confirm'] ==2){
                $sign['confirm']=3;
            }
            if(!empty($share)){
                $sign=array_merge($sign,$share);
            }
           
            db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update($sign);
            $id=$op['sign_id'];
        } else{
            $user_id=db('sign')->where(['user_id'=>$this->us['user_id']])->order('sign_id desc')->find();
            if ($user_id) {
                $hello   =explode('-', $user_id['contract'])[1];
                $contract=$this->us['number'] . '-' . ((int)$hello + 1);
            } else{
                $contract=$this->us['number'] . '-1';
            }
            $sign=[
                'idnumber' =>$data['idnumber'],
                'contract' =>$contract,
                'username' =>$data['username'],
                'order_id' =>$data['order_id'],
                'user_id'  =>$this->us['user_id'],
                'addtime'  =>strtotime($data['addtime']),
                'uptime'   =>strtotime($data['uptime']),
                'addres'   =>$data['addres'],
                'autograph'=>isset($data['autograph'])? $data['autograph'] : '',
                'ding'     =>0,
                'zhong'    =>0,
                'wei'      =>0,
                'b1'       =>0,
                'b2'       =>0,
                'b3'       =>0,
                'con_time' =>time(),
            ];
            if(!empty($share)){
                $sign=array_merge($sign,$share);
            }
            $id=db('sign')->insertGetId($sign);
        }
        
        r_date($id, 200);
    }
    
    /**
     * 电子报价合同确认提交
     *
     */
    public function ContractView()
    {
        $data=Request::instance()->post();
        $op  =db('sign')->where(['sign_id'=>$data['id']])->update(['contractpath'=>$data['img'], 'confirm'=>1]);
        
        r_date(null, 200);
    }
    
    /**
     * 电子报价显示
     */
    public function xian()
    {
        $data =Request::instance()->post();
        $order=db('order')->where('order_id', $data['order_id'])->field('contacts,ification,quotation')->find();
        $op   =db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->field('sign_id,username,idnumber,contract,addtime,uptime,addres,contractpath')->find();
        
        $op['username'] =$order['contacts'];
        $op['idnumber'] =!empty($op['idnumber'])? $op['idnumber'] : null;
        $op['contract'] =!empty($op['contract'])? $op['contract'] : null;
        $op['type']     =!empty($op['contractpath'])? 1 : 2;
        $op['addtime']  =!empty($op['addtime'])? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']   =!empty($op['uptime'])? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']   =!empty($op['addres'])? $op['addres'] : null;
        $op['quotation']=!empty($order['quotation'])? $order['quotation'] : null;
        $thro           =db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->order('th_time desc')->find();
        
        if ($thro) {
            $list     =1;
            $envelopes=db('envelopes')->where(['through_id'=>$thro['through_id']])->find();
        } else{
            $list     =2;
            $envelopes=db('envelopes')->where(['ordesr_id'=>$data['order_id'], 'through_id'=>0])->find();
        }
        if ($order['ification'] == 2) {
            $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type')->select();
            
            $s='';
            foreach ($capital as $item) {
                $s.=$item['capital_id'] . ',';
            }
            $s=substr($s, 0, - 1);  //利用字符串截取函数消除最后一个逗号
            if ($list == 1) {
                $yc=2;
            } else{
                $yc=1;
            }
            $allow             =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$s, 'envelopes_id'=>$envelopes['envelopes_id'], 'yc'=>$yc])->find();
            $envelopes['allow']=$allow['id'];
            if (!empty($envelopes['give_b'])) {
                $envelopes['give_b']=explode(',', $envelopes['give_b']);
            } else{
                $envelopes['give_b']=null;
            }
            if ($envelopes['capitalgo']) {
                $envelopes['capitalgo']=unserialize($envelopes['capitalgo']);
            } else{
                $envelopes['capitalgo']=null;
            }
            $envelopes['project_title']=empty($envelopes['project_title'])? '报价方案' : $envelopes['project_title'];
            $envelopes['yc']           =$list;
            
            $op=[
                'user'   =>$op,
                'gong'   =>$envelopes,
                'company'=>$capital,
            ];
        } else{
            $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,give_money,gong,capitalgo,fen')->select();
            foreach ($capital as $k=>$l) {
                $envelopes['give_money']=$l['give_money'];
                $envelopes['gong']      =!empty($l['gong'])? $l['gong'] : 0;
                if ($l['capitalgo']) {
                    $envelopes['capitalgo']=unserialize($l['capitalgo']);
                } else{
                    $envelopes['capitalgo']=null;
                }
                $envelopes['yc']       =$list;
                $capi[$k]['class_a']   =!empty($l['class_a'])? $l['class_a'] : null;
                $capi[$k]['class_b']   =!empty($l['class_b'])? $l['class_b'] : null;
                $capi[$k]['company']   =!empty($l['company'])? $l['company'] : null;
                $capi[$k]['square']    =!empty($l['square'])? $l['square'] : null;
                $capi[$k]['un_Price']  =!empty($l['un_Price'])? $l['un_Price'] : null;
                $capi[$k]['zhi']       =$l['zhi'];
                $capi[$k]['to_price']  =!empty($l['to_price'])? $l['to_price'] : null;
                $capi[$k]['capital_id']=!empty($l['capital_id'])? $l['capital_id'] : null;
                $capi[$k]['fen']       =!empty($l['fen'])? $l['fen'] : null;
                $capi[$k]['projectId'] =$l['projectId'];
                unset($capital[$k]);
            }
            $op=[
                'user'   =>$op,
                'gong'   =>!empty($envelopes)? $envelopes : null,
                'company'=>$capi,
            
            ];
            
        }
        
        r_date($op, 200);
    }
    
    /**
     * 基检
     */
    public function add_jian()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['company']) {
                $op=json_decode($data['company']);
                $op=$this->object2array($op);
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$product_chan['prices'],//单价
                            'rule'      =>$product_chan['price_rules'],//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>0,//状态
                            'to_price'  =>$product_chan['prices'] * $v['fang'],//总价
                            'crtime'    =>time(),
                            'ordesr_id' =>$data['order_id'],
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>1,//三
                        ];
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$product_chan['artificial'],//单价
                            'rule'      =>$product_chan['rmakes'],//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>1,//状态
                            'to_price'  =>$product_chan['artificial'] * $v['fang'],//总价
                            'crtime'    =>time(),
                            'ordesr_id' =>$data['order_id'],
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'qi_rmakes' =>'',
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>$v['type'],//三
                        ];
                        
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$v['prices'],//单价
                            'ordesr_id' =>$data['order_id'],
                            'rule'      =>'',//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>2,//状态
                            'to_price'  =>$v['fang'] * $v['prices'],//总价
                            'crtime'    =>time(),
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'qi_rmakes' =>'',
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>1,//三
                        ];
                        
                    }
                    
                    db('capital')->insertGetId($users);
                }
            }
            db('envelopes')->insertGetId([
                'wen_a'        =>$data['wen_a'],//一级分类
                'give_b'       =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                'ordesr_id'    =>$data['order_id'],
                'gong'         =>$data['gong'],
                'give_remarks' =>$data['give_remarks'],//备注
                'give_money'   =>$data['give_money'],//优惠金额
                'capitalgo'    =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                'project_title'=>$data['project_title'],
            
            ]);
            if (!empty($data['give_remarks'])) {
                db('through')->insertGetId([
                    'mode'     =>3,
                    'amount'   =>0,
                    'role'     =>2,
                    'admin_id' =>$this->us['user_id'],
                    'remar'    =>$data['give_remarks'],
                    'order_ids'=>$data['order_id'],
                    'baocun'   =>0,
                    'th_time'  =>time(),
                    'end_time' =>0,
                    'log'      =>'',//图片
                ]);
            }
            
            vendor('foxyzeng.huyi.HuYiSMS');
            $sms=new HuYiSMS();
            $us =db('order')->where('order_id', $data['order_id'])->value('telephone');
            if (preg_match("/^1[345678]{1}\d{9}$/", $us)) {
                $content="亲，益鸟工程师已经为您完成上门基检，您是否还满意呢？如果对报价和方案有任何疑问题，都可致电：4000987009，回T退订【益鸟维修】";
                $sms->duan($us, $content);
            }
            db('order')->where(['order_id'=>$data['order_id']])->update(['ification'=>2]);
            $cap=db('order')->where(['order_id'=>$data['order_id']])->field('ification,planned,appointment')->find();
            $pdf=$this->pdf->put($data['order_id'], 2, $cap);
            db('user')->where('user_id', $this->us['user_id'])->update(['lat'=>$data['lat'], 'lng'=>$data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime'=>substr($data['startTime'], 0, - 3), 'endTime'=>substr($data['endTime'], 0, - 3), 'user_id'=>$this->us['user_id'], 'order_id'=>$data['order_id'], 'time'=>time()]);
            //报价及时性
            db('quote')->insertGetId(['startTime'=>$cap['appointment'], 'planned'=>$cap['planned'], 'user_id'=>$this->us['user_id'], 'order_id'=>$data['order_id'], 'time'=>time()]);
            db('order')->where(['order_id'=>$data['order_id']])->update(['undetermined'=>0]);
            if ($pdf) {
                db()->commit();
                r_date(null, 200);
            }
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 基建自定义历史列表
     *
     */
    public function information()
    {
        $data=Request::instance()->post();
        if ($data['type'] == 1) {
            $object=db('information')->where(['types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes')->select();
            foreach ($object as $k=>$l) {
                $pr[$k]['projectId']   =$l['id'];
                $pr[$k]['projectMoney']=$l['un_Price'];
                $pr[$k]['projectTitle']=$l['class_b'];
                $pr[$k]['title']       =$l['company'];
                $pr[$k]['tao']         =$l['fen'];
                unset($object[$k]);
            }
            $pr=!empty($pr)? $pr : null;
        } else{
            $object=db('information')->where(['id'=>$data['id'], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes')->find();
            
            $pr['projectId']   =$object['id'];
            $pr['projectMoney']=$object['un_Price'];
            $pr['projectTitle']=$object['class_b'];
            $pr['title']       =$object['company'];
            $pr['tao']         =$object['fen'];
        }
        
        r_date($pr, 200);
    }
    
    /*
     *
     * 增加自定义历史记录
     */
    public function inf_add()
    {
        
        $data=Request::instance()->post();
        
        $op  =db('information')->insertGetId([
            'company'  =>$data['unit'],//单位
            'square'   =>$data['fang'],//方量
            'un_Price' =>$data['projectMoney'],//单价
            'zhi'      =>$data['zhi'],//质保
            'types'    =>1,//状态
            'fen'      =>3,//状态
            'to_price' =>$data['fang'] * $data['projectMoney'],//总价
            'crtime'   =>time(),
            'user_id'  =>$this->us['user_id'],
            'class_a'  =>$data['title'],//三
            'class_b'  =>$data['projectTitle'],//三
            'qi_rmakes'=>$data['qi_rmakes'],
        ]);
        $data=[
            'id'=>$op,
        ];
        r_date($data, 200);
    }
    
    /*
     *
     * 删除自定义历史记录
     */
    public function inf_dell()
    {
        
        $data=$this->model->post(['id']);
        
        $p=db('information')->where('id', $data['id'])->update(['types'=>2]);
        if ($p) {
            r_date([], 200);
        }
        r_date([], 300);
    }
    
    /**
     * 远程沟通外面
     */
    public function gou()
    {
        
        $data=Request::instance()->post();
        
        db()->startTrans();
        try {
            $cap='';
            if ($data['company']) {
                $op=json_decode($data['company'], true);
                
                
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['prices'],//单价
                            'rule'        =>$product_chan['price_rules'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>0,//状态
                            'to_price'    =>$product_chan['prices'] * $v['fang'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'crtime'      =>time(),
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>$v['type'],//三
                        ];
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['artificial'],//单价
                            'rule'        =>$product_chan['rmakes'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>1,//状态
                            'to_price'    =>$product_chan['artificial'] * $v['fang'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'crtime'      =>time(),
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>$v['type'],//三
                        ];
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$v['prices'],//单价
                            'rule'        =>'',//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>2,//状态
                            'to_price'    =>$v['fang'] * $v['prices'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'crtime'      =>time(),
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>1,//三
                        
                        ];
                    }
                    $p[]=$users['to_price'];
                    
                    if (isset($v['capital_id']) && $v['capital_id'] != 0) {
                        
                        db('capital')->where('capital_id', $v['capital_id'])->update($users);
                    } else{
                        
                        $capital=db('capital')->insertGetId($users);
                        $cap    .=$capital . ',';
                        $c      =substr($cap, 0, - 1);
                        
                    }
                }
            }
            if ($data['amount'] != 0.0) {
                $o=round(array_sum($p), 2);
                if ($o != $data['amount']) {
                    db()->rollback();
                    r_date(null, 300, '金额有误');
                } elseif (($o * 0.1) < $data['give_money']){
                    r_date(null, 300, '优惠金额不能大于订单总价的10%');
                }
            } else{
                $o=0;
            }
            
            if (!empty($data['through_id'])) {
                if (!empty($c)) {
                    $c=$data['capital_id'] . ',' . $c;
                } else{
                    $c=$data['capital_id'];
                }
                $p=db('through')->where('through_id', $data['through_id'])->update([
                    'mode'      =>$data['mode'],
                    'amount'    =>$o,
                    'remar'     =>$data['give_remarks'],
                    'order_ids' =>$data['order_id'],
                    'admin_id'  =>$this->us['user_id'],
                    'baocun'    =>$data['baocun'],
                    'th_time'   =>time(),
                    'end_time'  =>strtotime($data['end_time']),
                    'log'       =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id'=>!empty($c)? $c : '',
                ]);
                db('envelopes')->where('through_id', $data['through_id'])->update([
                    'wen_a'        =>$data['wen_a'],//一级分类
                    'give_b'       =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                    'ordesr_id'    =>$data['order_id'],
                    'give_remarks' =>$data['give_remarks'],//备注
                    'gong'         =>$data['gong'],
                    'capitalgo'    =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                    'give_money'   =>$data['give_money'],//优惠金额
                    'project_title'=>$data['project_title'],
                ]);
                if ($data['id']) {
                    db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
                }
            } else{
                $p=db('through')->insertGetId([
                    'mode'      =>$data['mode'],
                    'amount'    =>$o,
                    'remar'     =>$data['give_remarks'],
                    'order_ids' =>$data['order_id'],
                    'admin_id'  =>$this->us['user_id'],
                    'baocun'    =>$data['baocun'],
                    'th_time'   =>time(),
                    'end_time'  =>strtotime($data['end_time']),
                    'log'       =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id'=>!empty($c)? $c : '',
                
                ]);
                db('envelopes')->insertGetId([
                    'wen_a'        =>$data['wen_a'],//一级分类
                    'give_b'       =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                    'ordesr_id'    =>$data['order_id'],
                    'gong'         =>$data['gong'],
                    'give_remarks' =>$data['give_remarks'],//备注
                    'give_money'   =>$data['give_money'],//优惠金额
                    'capitalgo'    =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                    'through_id'   =>$p,
                    'project_title'=>$data['project_title'],
                ]);
            }
            
            $d=db('through')->where('order_ids', $data['order_id'])->select();
            $s='';
            foreach ($d as $item) {
                $s.=$item['through_id'] . ',';
            }
            
            $s=substr($s, 0, - 1);  //利用字符串截取函数消除最后一个逗号
            if ($data['baocun'] == 1) {
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'state'=>3, 'undetermined'=>0, 'ification'=>2, 'update_time'=>time()]);
                remind($data['order_id'], 3);
            }
            vendor('foxyzeng.huyi.HuYiSMS');
            $sms=new HuYiSMS();
            $us =db('order')->where('order_id', $data['order_id'])->find();
            if ($data['baocun'] == 0) {
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'ification'=>2, 'update_time'=>time()]);
                if ($us['state'] == 1) {
                    db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'state'=>2, 'undetermined'=>1, 'ification'=>2, 'update_time'=>time()]);
                }
                
            }
            $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
            }
            $remind=db('remind')->where(['order_id'=>$data['order_id'], 'admin_id'=>$this->us['user_id']])->find();
            if ($remind['tai'] != 0) {
                db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
            }
            
            $this->pdf->put($data['order_id'], 1, $us);
            $username=$this->us['username'];
            $content ="业主您好，我是益鸟维修店长工程师：{$username}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);
            
            db()->commit();
            r_date($p, 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通删除
     */
    public function deletion()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $p=db('through')->where('through_id', $data['through_id'])->field('capital_id')->find();
            db('capital')->where(['capital_id'=>['in', $p['capital_id']]])->delete();
            db('through')->where('through_id', $data['through_id'])->delete();
            db('envelopes')->where('through_id', $data['through_id'])->delete();
            if (isset($data['id']) && $data['id'] != 0) {
                db('allow')->where('id', $data['id'])->delete();
            }
            $d=db('through')->where('order_ids', $data['order_id'])->select();
            $s='';
            foreach ($d as $item) {
                $s.=$item['through_id'] . ',';
            }
            $s=substr($s, 0, - 1);  //利用字符串截取函数消除最后一个逗号
            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'update_time'=>time()]);
            db()->commit();
            r_date($p, 200, '删除成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通列表
     */
    public function gou_list()
    {
        $data=$this->model->post(['page'=>1, 'limit'=>10, 'order_ids']);
        $da  =db('through')->where(['capital_id'=>['neq', ' '], 'order_ids'=>$data['order_ids'], 'role'=>['neq', 3]])->field('amount,remar,th_time,capital_id,mode,through_id')->page($data['page'], $data['limit'])->order('th_time desc')->select();
        foreach ($da as $k=>$item) {
            $ca=db('envelopes')->where(['through_id'=>$item['through_id']])->field('give_money,project_title,envelopes_id')->find();
            if (!empty($item['capital_id'])) {
                $allow          =db('allow')->where(['order_id'=>$data['order_ids'], 'capital_id'=>$item['capital_id'], 'envelopes_id'=>$ca['envelopes_id'], 'yc'=>2])->find();
                $da[$k]['allow']=$allow['id'];
            } else{
                $da[$k]['allow']=null;
            }
            
            $da[$k]['amount']       =$item['amount'] - $ca['give_money'];
            $da[$k]['project_title']=empty($ca['project_title'])? '远程报价方案' : $ca['project_title'];
            $da[$k]['th_time']      =date('Y-m-d H:i:s', $item['th_time']);
            unset($da[$k]['capital_id']);
        }
        r_date($da, 200);
    }
    
    /**
     * 远程沟通里面
     */
    public function gou2()
    {
        
        $data=$this->model->post(['remar', 'order_id', 'end_time', 'mode', 'log']);
        try {
            $t=[
                'mode'     =>$data['mode'],
                'amount'   =>0,
                'role'     =>2,
                'admin_id' =>$this->us['user_id'],
                'remar'    =>$data['remar'],
                'order_ids'=>$data['order_id'],
                'baocun'   =>0,
                'th_time'  =>time(),
                'end_time' =>strtotime($data['end_time']),
                'log'      =>!empty($data['log'])? serialize(json_decode($data['log'], true)) : '',//图片
            ];
            
            db('through')->insertGetId($t);
            
            $d=db('through')->where('order_ids', $data['order_id'])->select();
            $s='';
            foreach ($d as $item) {
                $s.=$item['through_id'] . ',';
            }
            $s=substr($s, 0, - 1);
            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s]);
            //            vendor('foxyzeng.huyi.HuYiSMS');
            //            $sms=new HuYiSMS();
            //            $us=db('order')->where('order_id',$data['order_id'])->value('telephone');
            //            $content = "业主您好，我是益鸟维修店长工程师：{$user['username']}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通列表
     */
    public function get_gou()
    {
        $data=$this->model->post(['order_ids', 'gid']);
        $k   =db('through');
        if ($data['gid']) {
            if (strstr("店长", $data['gid'])) {
                $k->where(['role'=>[['eq', 2], ['neq', 3]]]);
            } elseif (strstr("客服", $data['gid'])){
                $k->where(['role'=>[['eq', 1], ['neq', 3]]]);
            } elseif (strstr("客户", $data['gid'])){
                $k->where(['role'=>[['eq', 4], ['neq', 3]]]);
            } else{
                $k->where(['role'=>[['eq', 6], ['neq', 3]]]);
            }
        } else{
            $k->where(['role'=>['neq', 3]]);
        }
        $h=$k->where(['order_ids'=>$data['order_ids']])->order('end_time asc,th_time desc')->select();
        foreach ($h as $k=>$value) {
            if ($value['log']) {
                $h[$k]['log']=unserialize($value['log']);
            } else{
                $h[$k]['log']=null;
            }
            $h[$k]['remar']  =!empty($value['remar'])? $value['remar'] : '';
            $h[$k]['th_time']=!empty($value['th_time'])? date('Y-m-d H:i:s', $value['th_time']) : null;
        }
        r_date($h, 200);
    }
    
    
    /************************************************************** 订单列表**************************************************************/
    /*
     *   0"全部" 1"新订单"2"待处理"3"带上门"4"待签约"5"施工中"6"已完工"7"已收藏"8"已取消"9"退单"10"待结算"11"被投诉"
     */
    
    public function get_order(OrderModel $orderModel)
    {
        
        $data=$this->model->post();
        $m   =$orderModel->table('order')
            ->alias('a')
            ->field('a.order_id,a.rework,a.ification,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.lat,a.lng,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,go.title,co.con_time,co.dep_money,co.weixin,st.dep,st.con,st.up_time,st.sta_time,be.tail,order.point,cos.type,a.undetermined,me.time as message_time,rework.customer,rework.master_id,a.cleared_time')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('contract co', 'a.contract_id=co.contract_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('message me', 'a.order_id=me.order_id and me.type=6 and a.assignor=me.user_id', 'left')
            ->join('cost cos', 'a.order_id=cos.order_id ', 'left')
            ->join('order_rework rework', 'a.order_id=rework.order_id ', 'left');
        
        if (isset($data['title']) && $data['title'] != '') {
            $m->where(['a.contacts|a.telephone|a.addres|go.title'=>['like', "%{$data['title']}%"]]);
        }
        if (isset($data['created_time']) && $data['created_time'] != '' && $data['created_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['created_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.created_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        if (isset($data['state']) && $data['state'] != '' && $data['state'] != 0) {
            if ($data['state'] == 1) {
                $m->where(['a.state'=>1]);
            } elseif ($data['state'] == 2){
                $m->where('a.through_id !=NULL or a.undetermined=1');
                $m->where(['a.state'=>['<', 4]]);
            } elseif ($data['state'] == 3){
                $m->where(['a.state'=>2]);
            } elseif ($data['state'] == 4){
                $m->where(['a.state'=>3]);
            } elseif ($data['state'] == 5){
                $m->where(['a.state'=>['between', [4, 5]]]);
            } elseif ($data['state'] == 6){
                $m->where(['a.state'=>['between', [6, 7]]]);
            } elseif ($data['state'] == 7){
                $m->where(['a.point'=>2]);
            } elseif ($data['state'] == 8){
                $m->where(['a.state'=>8]);
            } elseif ($data['state'] == 9){
                $m->where(['a.state'=>9]);
            } elseif ($data['state'] == 10){
                $m->where(['cos.type'=>1]);
            } elseif ($data['state'] == 11){
                $order=send_post(UIP_SRC . '/support-v1/order/complaint?column=order_id&response_type=string', [], 2);
                $order=json_decode($order, true);
                $m->where(['a.order_id'=>['in', $order['data']]]);
            } elseif ($data['state'] == 12){
                $m->whereNotNull('a.cleared_time');
                $m->where('a.cleared_time');
            }
            if ($data['state'] != 7) {
                if ($data['state'] != 2) {
                    $m->where(['a.undetermined'=>0]);
                } else{
                    $m->where(['a.undetermined'=>1]);
                }
            }
            
        } else{
            $m->where(['a.state'=>['neq', 10]]);
        }
        if (isset($data['user_id']) && $data['user_id'] != 0) {
            $m->where(['a.assignor'=>$data['user_id']]);
        } else{
            $m->where(['a.assignor'=>$this->us['user_id']]);
        }
        $list=$m->page($data['page'], $data['limit'])->order('me.time desc')->select();
        foreach ($list as $k=>$key) {
            $list[$k]['con_time']    =!empty($key['con_time'])? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['up_time']     =!empty($key['up_time'])? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['sta_time']    =!empty($key['sta_time'])? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['created_time']=!empty($key['created_time'])? date('Y-m-d H:i', $key['created_time']) : '';
            $list[$k]['planned']     =!empty($key['planned'])? date('Y-m-d H:i:s', $key['planned']) : '';
            $offer                   =$orderModel::offer($key['order_id']);
            $list[$k]['amount']      =$offer['amount'];
            $list[$k]['yu']          =$offer['yu'];
            $list[$k]['yc']          =$offer['yc'];
            $list[$k]['gong']        =$offer['gong'];
            $list[$k]['message_time']=put_time($key['message_time']);
            if (!empty($key['cleared_time'])) {
                $list[$k]['settlement']=1;
            } else{
                $list[$k]['settlement']=0;
            }
            $i                   =db('through')->where(['order_ids'=>$key['order_id'], 'role'=>2])->field('end_time,th_time')->order('through_id desc')->find();
            $list[$k]['end_time']=!empty($i['end_time'])? date('Y-m-d H:i:s', $i['end_time']) : '';
            $list[$k]['remind']  =db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$key['order_id']])->value('tai');
        }
        
        r_date(array_merge($list));
    }
    
    /**
     * 订单详情
     */
    public function get_info(OrderModel $orderModel)
    {
        $data=$this->model->post();
        if (empty($data['order_id'])) {
            r_date([], 300, '参数错误');
        }
        if (!empty($data['user_id'])) {
            $this->us['user_id']=$data['user_id'];
        }
        $re=db('order')
            ->field('order.order_id,order.ification,order.rework,order.logo,order.order_no,order.lat,order.lng,order.addres,order.contacts,order.telephone,order.remarks,order.created_time,order.state,order.quotation,order.planned,b.title,p.province,c.city,y.county,go.title,co.con_time,co.type,co.contract,co.deposit,co.dep_money,st.invoice,st.sta_time,st.dep,st.con,st.up_time,st.sta_time,be.logos,be.tail,ac.full,order.label_id,order.point,re.tai,me.time as message_time,rework.customer,rework.reason as rewordDes,comp.reason,rework.master_id,sin.contractpath,order.cleared_time')
            ->join('chanel b', 'order.channel_id=b.id', 'left')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('contract co', 'order.contract_id=co.contract_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('product ac', 'order.product_id=ac.product_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->join('message me', 'order.order_id=me.order_id and me.type=6', 'left')
            ->join('remind re', 'order.order_id=re.order_id', 'left')
            ->join('order_rework rework', 'order.order_id=rework.order_id ', 'left')
            ->join('sign sin', 'order.order_id=sin.order_id ', 'left')
            ->join('complaint comp', 'order.order_id=comp.order_id ', 'left');
        if (isset($data['type']) && $data['type'] != '') {
            $re->where(['u.reserve'=>2]);
        } else{
            $re->where(['order.assignor'=>$this->us['user_id']]);
        }
        $res=$re->where(['order.order_id'=>$data['order_id']])->find();
      
        if ($res) {
            $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
            }
            if ($res['tai'] != 0) {
                db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
            }
            $res['planned']     =!empty($res['planned'])? date('Y-m-d H:i', $res['planned']) : null;
            $res['logo']        =!empty($res['logo'])? unserialize($res['logo']) : null;
            $res['contract']    =!empty($res['contract'])? unserialize($res['contract']) : null;
            $res['autograph']   =!empty($res['contractpath'])? $res['contractpath'] : null;
            $res['deposit']     =!empty($res['deposit'])? unserialize($res['deposit']) : null;
            $res['sta_time']    =!empty($res['sta_time'])? date('Y-m-d H:i', $res['sta_time']) : null;
            $res['inside']      =!empty($res['inside'])? $res['inside'] : null;
            $res['up_time']     =!empty($res['up_time'])? date('Y-m-d H:i', $res['up_time']) : null;
            $res['tui_time']    =!empty($res['tui_time'])? date('Y-m-d H:i', $res['tui_time']) : null;
            $res['con_time']    =!empty($res['con_time'])? date('Y-m-d H:i', $res['con_time']) : null;
            $res['created_time']=!empty($res['created_time'])? date('Y-m-d H:i', $res['created_time']) : null;
            $res['message_time']=!empty($res['message_time'])? date('Y-m-d H:i', $res['message_time']) : null;
            $res['uptime']      =!empty($res['uptime'])? date('Y-m-d H:i', $res['uptime']) : null;
            $res['settlement']  =!empty($res['cleared_time'])? 1 : 0;
            $res['yu']          =0;
            $i                  =db('through')->where(['order_ids'=>$data['order_id'], 'role'=>2])->field('end_time')->order('through_id desc')->find();
            $res['end_time']    =!empty($i['end_time'])? date('Y-m-d H:i:s', $i['end_time']) : null;
            $shi['ids']         =$res['master_id'];
            if (!empty($shi['ids'])) {
                $results=send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                $results=json_decode($results, true);
                if ($results['code'] == 200) {
                    if (!empty($results['data'])) {
                        $res['master_username']=$results['data'];
                    } else{
                        $res['master_username']=null;
                    }
                } else{
                    $res['master_username']=null;
                }
                
            } else{
                $res['master_username']=null;
            }
            
            //签约金额
            $offer=$orderModel::offer($data['order_id']);
            //材料领用
            $material_usage          =db('material_usage')->where('status', 1)->where(['order_id'=>$data['order_id']])->sum('total_price');
            $material_material       =db('material_usage')->where('status', 1)->where(['order_id'=>$data['order_id'], 'type'=>2, 'status'=>0])->count();
            $res['material_usage']   =$material_usage;
            $res['material_material']=$material_material;
            //费用报销
            $reimbursement=db('reimbursement')->where(['order_id'=>$data['order_id'], 'status'=>1])->sum('money');
            $Material_To  =db('reimbursement')->where(['order_id'=>$data['order_id'], 'type'=>2, 'status'=>0])->count();
            
            $res['reimbursement']=$reimbursement;
            $res['material_To']  =$Material_To;
            $res['yc']           =$offer['yc'];
            $res['p']            =$offer['amount'];
            $res['payment']      =1;
            $res['system_time']  =time();
            if (!empty($res['dep_money']) && $res['dep_money'] != 0.00) {
                $res['yu']=$res['p'] - $res['dep_money'];
            }
            $res['yu']=$res['p'] - $res['dep_money'] - $res['dep'] - $res['tail'];
            $res['yu']=$offer['yu'];
            $pa       =db('payment')->where(['orders_id'=>$res['order_id']])->order('payment_id desc')->field('money,weixin')->find();
            if ($pa) {
                $res['dep_money']=$pa['money'];
                if ($pa['weixin'] == 2) {
                    $payment=db('recharge')->where(['order_no'=>$res['order_no'], 'status'=>1, 'type'=>2, 'money'=>$pa['money']])->find();
                    if (!$payment) {
                        $res['payment']=2;
                    }
                }
            }
            $order_for_turnover=0;
            $da['ification']   =$res['ification'];
            $da['order_id']    =$res['order_id'];
            $kl[]              =$da;
            $thro              =db('through')->where(['order_ids'=>$res['order_id'], 'baocun'=>1])->field('baocun,through_id,amount')->order('th_time desc')->find();
            if ($thro['baocun'] == 1) {
                $ca                =db('envelopes')
                    ->where(['through_id'=>$thro['through_id']])
                    ->field('give_money,gong')
                    ->find();
                $order_for_turnover+=$thro['amount'] - $ca['give_money'];
            } else{
                $cap               =db('capital')
                    ->where(['ordesr_id'=>$res['order_id'], 'types'=>1, 'enable'=>1])
                    ->sum('to_price');
                $ca                =db('envelopes')
                    ->where(['ordesr_id'=>$res['order_id'], 'through_id'=>0])
                    ->field('give_money,gong')->find();
                $order_for_turnover+=$cap - $ca['give_money'];
            }
            $capital=$cap=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->field('class_b,capital_id')->column('capital_id');
            if (!empty($capital)) {
                $sql="SELECT SUM(`personal_price`) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`capital_id` in(" . implode(',', $capital) . ")";
                
                //dd($sql);
                //原生sql
                $reality_artificial=Db::connect(config('database.db2'))->table('app_user_order_capital');
                $sum               =$reality_artificial->query($sql);
                if (isset($sum[0]['sum'])) {
                    $order_for_reality_artificial=round($sum[0]['sum'], 2);
                } else{
                    $order_for_reality_artificial=0;
                }
            } else{
                $order_for_reality_artificial=0;
            }
            
            //ds($reality_artificial);
            //dd($sum[0]['sum']);
            //ds(Db::connect('db3')->name('app_user_order_capital'));
            
            $res['order_for_reality_artificial']=$order_for_reality_artificial;
//            //预计利润
            $res['estimate']=sprintf("%.2f", ($order_for_turnover - order_for_artificial($kl) - order_for_Finance($kl) - order_for_outlay($kl)));
            
            //实际利润
            $res['actual']=sprintf("%.2f", ($order_for_turnover - $order_for_reality_artificial - order_for_reality_material($kl) - order_for_outlay($kl)));
            
            
        } else{
            $res=null;
        }
        
        r_date($res);
    }
    
    /*
     * 待处理
     */
    public function PendingDisposal()
    {
        $data   =$this->model->post(['order_id']);
        $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
        if ($message['already'] != 0) {
            db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
        }
        $res=db('remind')->where(['order_id'=>$data['order_id'], 'admin_id'=>$this->us['user_id']])->value('tai');
        if ($res != 0) {
            db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
        }
        db('order')->where(['order_id'=>$data['order_id']])->update(['undetermined'=>1, 'state'=>2]);
        
        r_date([], 200);
    }
    
    /*
     * 沟通记录详情
     *
     */
    public function get_quote()
    {
        
        $data=$this->model->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id']=$data['user_id'];
        }
        $res=db('order')
            ->field('order.order_id,order.logo,order.order_no,order.addres,order.contacts,order.telephone,order.remarks,p.province,c.city,y.county,go.title')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where(['order.order_id'=>$data['order_id'], 'order.assignor'=>$this->us['user_id']])
            ->find();
        if ($res) {
            $res['logo']   =!empty($res['logo'])? unserialize($res['logo']) : null;
            $res['remarks']=!empty($res['remarks'])? $res['remarks'] : '';
            if (!empty($data['through_id'])) {
                $res['gou']=db('through')->where(['through_id'=>$data['through_id']])->field('through_id,amount,remar,mode,th_time,log,end_time,capital_id')->order('th_time desc')->find();
                
            }
            if (!empty($res['gou'])) {
                $ca                         =db('envelopes')->where(['through_id'=>$res['gou']['through_id']])->field('give_money,gong,give_b,wen_a,project_title,envelopes_id')->find();
                $res['gou']['give_money']   =$ca['give_money'];
                $res['gou']['gong']         =$ca['gong'];
                $res['gou']['remar']        =!empty($res['gou']['remar'])? $res['gou']['remar'] : null;
                $res['gou']['give_b']       =!empty($ca['give_b'])? explode(',', $ca['give_b']) : null;
                $res['gou']['wen_a']        =!empty($ca['wen_a'])? $ca['wen_a'] : '';
                $res['gou']['project_title']=$ca['project_title'];
                if ($res['gou']['capital_id']) {
                    $allow              =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$res['gou']['capital_id'], 'envelopes_id'=>$ca['envelopes_id'], 'yc'=>2])->find();
                    $res['gou']['allow']=$allow['id'];
                    $capital_id         =explode(',', $res['gou']['capital_id']);
                    foreach ($capital_id as $item) {
                        $res['gou']['company'][]=db('capital')->where(['capital_id'=>$item, 'types'=>1])->field('class_a,class_b,company,square,un_Price,zhi,fen,capital_id,gold_suite as type,projectId')->find();
                    }
                    foreach ($res['gou']['company'] as $k=>$m) {
                        if ($m['fen'] == 0) {
                            $pro                                  =db('product_chan')->where(['product_id'=>$m['projectId']])->field('product_id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['product_id'];
                        } elseif ($m['fen'] == 1){
                            $pro                                  =db('detailed')->where(['detailed_id'=>$m['projectId']])->field('detailed_id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['detailed_id'];
                        } else{
                            $pro                                  =db('information')->where(['class_b'=>$m['class_b'], 'types'=>1, 'user_id'=>$this->us['user_id'], 'un_Price'=>$m['un_Price']])->field('id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['id'];
                        }
                        $res['gou']['company'][$k]['capital_id']=$m['capital_id'];
                    }
                }
                $res['gou']['log']     =!empty($res['gou']['log'])? unserialize($res['gou']['log']) : null;
                $res['gou']['th_time'] =!empty($res['gou']['th_time'])? date("Y-m-d H:i", $res['gou']['th_time']) : '';
                $res['gou']['end_time']=!empty($res['gou']['end_time'])? date("Y-m-d H:i", $res['gou']['end_time']) : '';
                
            } else{
                $res['gou']=null;
            }
            
        } else{
            $res='';
        }
        
        
        r_date($res);
    }
    
    /**
     * 报价信息
     */
    public function get_jia()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->select();
        foreach ($s as $o=>$y) {
            $s[$o]['capitalgo']=!empty($y['capitalgo'])? unserialize($y['capitalgo']) : null;
            $s1                =db('order')->where(['order_id'=>$data['order_id']])->value('state');
            if ($s1 < 4) {
                $o8=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'programme'=>2])->select();
                if ($o8) {
                    $s[$o]['sisi']=1;
                } else{
                    $s[$o]['sisi']=0;
                }
            } else{
                $s[$o]['sisi']=0;
            }
        }
        $sign=db('sign')->where(['order_id'=>$data['order_id']])->find();
        $o   =[
            0=>$s,
            1=>empty($sign)? '' : $sign,
        ];
        r_date($o, 200);
    }
    
    /**
     * 远程报价详情
     */
    public function get_yc()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->select();
        $da  =[
            0=>$s,
        ];
        
        r_date($da, 200);
    }
    
    /**
     * 是否报价了
     */
    public function get_cha()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->find();
        if ($s) {
            r_date([], 300);
        } else{
            r_date([], 200);
        }
        
        
    }
    
    /*********************************************************************** * 重点标签***************************************************************************  */
    
    
    /**
     * 获取标签
     */
    public function get_label()
    {
        $res=db('label')->where(['user_id'=>['eq', 0]])->select();
        $rss=db('label')->where('user_id', $this->us['user_id'])->select();
        if ($rss) {
            $o=array_merge($res, $rss);
        } else{
            $o=$res;
        }
        
        r_date(array_values($o));
    }
    
    /**
     * 标记
     */
    public function point()
    {
        $data=$this->model->post(['type', 'order_id']);
        $b   =db('order')->where('order_id', $data['order_id'])->update(['point'=>$data['type']]);
        r_date([], 200);
    }
    
    /*
     * 用户端显示报价
     */
    public function allow()
    {
        $data              =$this->model->post(['order_id', 'capital_id', 'envelopes_id', 'yc']);
        $data['capital_id']=substr($data['capital_id'], 0, - 1);
        if ($data['yc'] == 1) {
            $yc=2;
        } else{
            $yc=1;
        }
        $allow=db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$data['capital_id'], 'envelopes_id'=>$data['envelopes_id'], 'yc'=>$yc])->find();
        
        if (empty($allow)) {
            db('allow')->insertGetId([
                'order_id'    =>$data['order_id'],
                'capital_id'  =>$data['capital_id'],
                'envelopes_id'=>$data['envelopes_id'],
                'yc'          =>$yc,
                'time'        =>time(),
            ]);
        }
        r_date([], 200);
    }
    
    /*
    * 用户端显示报价
    */
    public function all()
    {
        $data=$this->model->post(['through_id', 'order_id', 'yc']);
        if ($data['yc'] == 1) {
            $yc=2;
        } else{
            $yc=1;
        }
        $through  =db('through')->where('through_id', $data['through_id'])->find();
        $envelopes=db('envelopes')->where('through_id', $data['through_id'])->find();
        $allow    =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$through['capital_id'], 'envelopes_id'=>$envelopes['envelopes_id'], 'yc'=>$yc])->find();
        if (empty($allow)) {
            db('allow')->insertGetId([
                'order_id'    =>$data['order_id'],
                'capital_id'  =>$through['capital_id'],
                'envelopes_id'=>$envelopes['envelopes_id'],
                'yc'          =>$yc,
                'time'        =>time(),
            ]);
        }
        r_date([], 200);
    }
    
    /*** ************************************************************确认时间***************************************************
     **************************************************************** types等于1是需要改变订单状态* types等于2是只需修改上门时间 */
    
    
    public function get_planned()
    {
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms =new HuYiSMS();
        $data=$this->model->post(['order_id', 'planned', 'types', 'nodian']);
        $us  =db('order')->where('order_id', $data['order_id'])->field('telephone,planned,undetermined')->find();
        if ($data['types'] == 1) {
            if ($us['undetermined'] == 1) {
                orderModel::update(['undetermined'=>0], ['order_id'=>$data['order_id']]);
            }
            db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['planned'=>strtotime($data['planned']), 'state'=>2, 'update_time'=>time(), 'appointment'=>time()]);
            $user   =$this->us['username'];
            $content="业主您好，我是刚与您通话的益鸟维修店长工程师{$user}，和您约定{$data['planned']}为您上门检测，我将准时到达。如有问题，请及时联系联系：4000987009～回T退订【益鸟维修】";
            if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                $sms->duan($us['telephone'], $content);
            }
            if ($data['nodian'] != 1) {
                remind($data['order_id'], 2);
            }
            $y=[
                'planneds'=>'',
                'planned' =>[],
            ];
        } elseif ($data['types'] == 2){
            db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['planned'=>strtotime($data['planned']), 'update_time'=>time(), 'appointment'=>time()]);
            if (!empty($us['planned'])) {
                db('planned')->insertGetId([
                    'order_id'=>$data['order_id'],
                    'planned' =>$us['planned'],
                ]);
            }
            $y=[
                'planneds'=>'',
                'planned' =>[],
            ];
            
        } elseif ($data['types'] == 3){
            $y=db('planned')->where(['order_id'=>$data['order_id']])->field('planned')->order('id desc')->select();
            if (!empty($y)) {
                foreach ($y as $k=>$value) {
                    $y[$k]=!empty($value['planned'])? date("Y-m-d H:i", $value['planned']) : '';
                }
                $y=[
                    'planneds'=>!empty($us['planned'])? date("Y-m-d H:i", $us['planned']) : '',
                    'planned' =>!empty($y)? $y : [],
                ];
            } else{
                $y=[
                    'planneds'=>!empty($us['planned'])? date("Y-m-d H:i", $us['planned']) : '',
                    'planned' =>[],
                ];
            }
        }
        if ($y) {
            r_date($y, 200);
        }
        r_date([], 300);
    }
    
    
    /**
     * 取消订单/退单子
     */
    public function get_reason()
    {
        $data=$this->model->post(['order_id', 'reason', 'tui_moey']);
        if (empty($data['tui_moey'])) {
            if (empty($data['reason'])) {
                r_date([], 300);
            }
            $data=db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['state'=>8, 'reason'=>$data['reason'], 'tui_time'=>time(), 'update_time'=>time()]);
        } else{
            if (empty($data['reason'])) {
                r_date([], 300);
            } elseif (empty($data['tui_moey'])){
                r_date([], 300);
            }
            $data=db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['state'=>9, 'reason'=>$data['reason'], 'tui_moey'=>$data['tui_moey'], 'tui_state'=>1, 'tui_time'=>time(), 'update_time'=>time()]);
        }
        
        if ($data) {
            r_date($data);
        }
        r_date([], 300);
    }
    
    /**
     * 签约
     */
    public function qian()
    {
        $data=$this->model->post(['contract', 'deposit', 'dep_money', 'order_id', 'type', 'weixin', 'contracType']);
        try {
            
            $kl          =[
                'contract'   =>!empty($data['contract'])? serialize(json_decode($data['contract'], true)) : '',//合同
                'con_time'   =>time(),
                'deposit'    =>'',
                'orders_id'  =>$data['order_id'],
                'type'       =>$data['type'],
                'weixin'     =>$data['weixin'],
                'contracType'=>$data['contracType'],//1合同拍照2电子合同
            ];
            $contractpath=db('sign')->where('order_id', $data['order_id'])->value('contractpath');
            if ($data['contracType'] == 1 && empty($data['contract'])) {
                throw new Exception('合同照片不能为空');
            } elseif ($data['contracType'] == 2 && empty($contractpath)){
                throw new Exception('请联系客户签字');
            }
            $contr=db('contract')->where('orders_id', $data['order_id'])->find();
            if ($contr) {
                db('contract')->where('orders_id', $data['order_id'])->update($kl);
            } else{
                $res=db('contract')->insertGetId($kl);
            }
            db('payment')->insertGetId([
                'uptime'   =>time(),
                'logos'    =>!empty($data['deposit'])? serialize(json_decode($data['deposit'], true)) : '',//图片
                'money'    =>$data['dep_money'],//尾款
                'orders_id'=>$data['order_id'],
                'weixin'   =>$data['weixin'],
            ]);
            //type等于1提交 2微信 等于1现金
            if ($data['type'] == 1) {
                
                if ($data['weixin'] == 1) {
                    if (empty($contr)) {
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['state'=>4, 'contract_id'=>$res, 'update_time'=>time()]);
                        remind($data['order_id'], 4);
                    } else{
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['update_time'=>time(), 'state'=>4]);
                    }
                    
                } else{
                    if (empty($contr)) {
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['contract_id'=>$res, 'update_time'=>time()]);
                    } else{
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['update_time'=>time()]);
                    }
                }
                
            } else{
                if (empty($contr)) {
                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['contract_id' => $res, 'update_time' => time()]);
                }
               
                
            }
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     *
     * 开工设置
     */
    public function userlist()
    {
        $data=$this->model->post(['order_id']);
        $de  =db('startup')->where('orders_id', $data['order_id'])->field('sta_time,up_time,con,handover,xiu_id')->find();
        if ($de) {
            $shi['ids']     =$de['xiu_id'];
            $shi['order-id']=$data['order_id'];
            if (!empty($shi['ids'])) {
                $results=send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                $results=json_decode($results);
                if ($results->code == 200) {
                    $de['shi']=object_array($results->data);
                } else{
                    $de['shi']='';
                }
            } else{
                $de['shi']=[];
            }
            $de['sta_time']=!empty($de['sta_time'])? date('Y-m-d H:i', $de['sta_time']) : '';
            $de['up_time'] =!empty($de['up_time'])? date('Y-m-d H:i', $de['up_time']) : '';
            $de['handover']=!empty($de['handover'])? unserialize($de['handover']) : null;
        } else{
            $de=null;
        }
        
        r_date($de, 200);
        
        
    }
    
    /*
     * 获取师傅
     */
    public function get_master()
    {
        $data                =$this->model->post(['username']);
        $dat['username']     =$data['username'];
        $dat['sort_store_id']=$this->us['store_id'];
        $result              =send_post(UIP_SRC . "/support-v1/user/old-list", $dat);
        $results             =json_decode($result);
        if ($results->code == 200) {
            $de['chen']=$results->data;
        } else{
            $de['chen']=null;
        }
        r_date($de, 200);
    }
    
    /*
        *
        * 联系工程师
        */
    public function engineer()
    {
        $data   =$this->model->post(['order_id']);
        $results=send_post(UIP_SRC . "/support-v1/user/order-user", ['order_id'=>$data['order_id']]);
        $results=json_decode($results);
        if ($results->code == 200) {
            $da['chen']=$results->data;
            
            r_date($da, 200);
        } else{
            r_date([], 300, $results->msg);
        }
        
    }
    
    /*
     * 开工设置
     */
    public function startup_settings()
    {
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms =new HuYiSMS();
        $data=$this->model->post(['con', 'sta_time', 'up_time', 'order_id', 'shi_id', 'handover', 'leader']);
        if (!empty($data['up_time']) && !empty($data['sta_time'])) {
            if (strtotime($data['sta_time']) > strtotime($data['up_time'])) {
                r_date([], 300, "开工时间必须早于等于完工时间");
            }
        }
        db()->startTrans();
        try {
            $res=db('startup')->where(['orders_id'=>$data['order_id']])->find();
            if ($res) {
                
                $o=[
                    'con'     =>$data['con'],//备注
                    'sta_time'=>strtotime($data['sta_time']),
                    'up_time' =>strtotime($data['up_time']),
                    'xiu_id'  =>$data['shi_id'],
                    'handover'=>!empty($data['handover'])? serialize(json_decode($data['handover'], true)) : '',//图片,
                ];
                db('startup')->where('orders_id', $data['order_id'])->update($o);
            } else{
                $res=db('startup')
                    ->insertGetId([
                        'con'      =>$data['con'],//备注
                        'sta_time' =>strtotime($data['sta_time']),
                        'up_time'  =>strtotime($data['up_time']),
                        'orders_id'=>$data['order_id'],
                        'xiu_id'   =>$data['shi_id'],
                        'handover' =>!empty($data['handover'])? serialize(json_decode($data['handover'], true)) : '',//图片,
                    ]);
                
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['startup_id'=>$res]);
            }
            
            $us=db('order')
                ->field('order.ification,order.telephone,co.con_time,order.pro_id2')
                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                ->where('order_id', $data['order_id'])
                ->find();
            
            if ($us['ification'] == 2) {
                $thro=db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->order('th_time desc')->find();
                if ($thro) {
                    $ca=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money,gong')->find();
                } else{
                    $ca=db('envelopes')->where(['ordesr_id'=>$data['order_id'], 'through_id'=>0])->field('give_money,gong')->find();
                }
            } else{
                $ca=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->field('sum(to_price),sum(give_money),gong')->order('capital_id desc')->find();
            }
            $uss['order_id']      =$data['order_id'];
            $uss['remark']        =$data['con'];
            $uss['user_ids']      =$data['shi_id'];
            $uss['plan_start_at'] =strtotime($data['sta_time']);
            $uss['plan_end_at']   =strtotime($data['up_time']);
            $uss['plan_work_time']=$ca['gong']; //师傅ID
            $uss['leader']        =$data['leader']; //师傅ID
            $uss['ascription']    =$this->us['store_id']; //师傅ID
            $uss['con_time']      =$us['con_time']; //师傅ID
            $uss['store_id']      =$this->us['store_id']; //师傅ID
            $result               =send_post(UIP_SRC . "/support-v1/order/add", $uss);
            $results              =json_decode($result);
            if ($results->code == 200) {
                $uscapital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1])->field('wen_c')->select();
                if ($uscapital) {
                    if ($us['pro_id2'] != 129 && $uscapital[0]['wen_c'] != '暗埋水管打压检测') {
                        if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                            $content="亲，感谢选择益鸟维修，已定于{$data['sta_time']}正式开工，请悉知。若需要修改开工时间或增加施工项目，请及时与工程师进行沟通~若有任何需要，请及时联系：4000987009～回T退订【益鸟维修】";
                            $sms->duan($us['telephone'], $content);
                        }
                        
                    }
                }
                db()->commit();
                r_date([], 200, '新增成功');
            } else{
                r_date([], 300, $results->msg);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /**
     * 发起收款
     */
    public function payment(OrderModel $orderModel)
    {
        $data=$this->model->post(['logos', 'weixin', 'orders_id', 'money']);
        
        if ($data['money'] < 0) {
            r_date([], 300, '请输入正确金额');
        }
        if ($data['weixin'] == 1 && empty($data['logos'])) {
            
            r_date([], 300, '请上传图片');
        }
        $res=db('payment')->insertGetId([
            'uptime'   =>time(),//实际完工时间
            'logos'    =>!empty($data['logos'])? serialize(json_decode($data['logos'], true)) : '',//图片
            'money'    =>$data['money'],//尾款
            'orders_id'=>$data['orders_id'],
            'weixin'   =>$data['weixin'],
        ]);
        if ($res) {
            $list=$orderModel->offer($data['orders_id'], 2);
            if ($list['yu'] == 0) {
                db('order')->where(['order_id'=>$data['orders_id']])->update(['received_time'=>time()]);
            }
            r_date([], 200, '新增成功');
        } else{
            r_date([], 300, '操作失败');
        }
    }
    
    
    function object2array(&$object)
    {
        $object=json_decode(json_encode($object), true);
        return $object;
    }
    
    public function unit()
    {
        $object=db('unit')->field('title,id')->select();
        
        r_date($object, 200);
    }
    
    
    /**
     * 视频节点
     */
    public function jie()
    {
        
        $data   =$this->model->post(['order_ids']);
        $results=send_post(UIP_SRC . "/support-v1/node/list?order_id=" . $data['order_ids'], [], 2);
        $results=json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);
        } else{
            r_date([], 200, $results->msg);
        }
        
    }
    
    
    /*
    *
    * 订单发起返工
    */
    public function fan()
    {
        $data=$this->model->post();
        db()->startTrans();
        try {
            $order_rework=db('order_rework')->where(['order_id'=>$data['order_id']])->find();
            if (empty($order_rework)) {
                db('order_rework')->insertGetId([
                    'master_id'=>$data['master_id'],
                    'user_id'  =>$this->us['user_id'],
                    'order_id' =>$data['order_id'],
                    'reason'   =>$data['reason'],
                    'customer' =>2,
                ]);
                $source=2;
                db('order')->where('order_id', $data['order_id'])->update(['rework'=>1]);
            } else{
                db('order_rework')->where(['order_id'=>$data['order_id']])->update([
                    'master_id'=>$data['master_id'],
                    'user_id'  =>$this->us['user_id'],
                    'reason'   =>$data['reason'],
                ]);
                $source=$order_rework['customer'];
            }
            $order=OrderModel::get(['order_id', $data['order_id']]);
            if ($order->state > 5) {
                $type=1;
            } else{
                $type=2;
            }
            $result =send_post(UIP_SRC . "/support-v1/rework/add", ['order_id'=>$data['order_id'], 'user_ids'=>$data['master_id'], 'type'=>$type, 'source'=>$source, 'reason'=>$data['reason']]);
            $results=json_decode($result, true);
            if ($results['code'] == 200) {
                db()->commit();
                r_date([], 200, '新增成功');
            } else{
                db()->rollback();
                r_date([], 300, $results['msg']);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
    *
    * 获取返工原因状态
    */
    public function ReturnWorkReson()
    {
        $data            =$this->model->post();
        $re              =db('order_rework')->where(['order_id'=>$data['order_id']])->field('reason')->find();
        $reason['reason']=$re['reason'];
        r_date($reason, 200);
        
    }
    
    /*
     * 订单发起完工
     */
    public function ToBeFinished()
    {
        $data              =$this->model->post(['order_id']);
        $result            =send_post(UIP_SRC . "/support-v1/order/all-finish", ['order_id'=>$data['order_id']]);
        $results           =json_decode($result, true);
        $reality_artificial=Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$data['order_id']])->select();
        $time              =[];
        foreach ($reality_artificial as $value) {
            $time[]=$value['finish_at'];
        }
        $max_time=array_search(max($time), $time);
        if ($results['code'] == 200) {
            OrderModel::update(['state'=>7, 'finish_time'=>$time[$max_time]], ['order_id'=>$data['order_id']]);
            r_date([], 200);
        } else{
            r_date([], 300, $results->msg);
        }
    }
    
    
}